import React, { Suspense, useState, useEffect } from "react";
import { useHistory } from "react-router-dom";
import { Tabs, message } from 'antd';
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import actions from "@/shared/actions";

import Home from "./pages/home";
import List from "./pages/list";

const { TabPane } = Tabs;

const menus = [
  {
    key: "platform",
    route: "/",
    title: "主页",
  },
  {
    key: "platform-list",
    route: "/list",
    title: "列表页",
  }
];

const BASE_NAME = window.__POWERED_BY_QIANKUN__ ? "/platform" : "";

const App = () => {
  const [refresh, setRefresh] = useState(0);
  const [selectedKeys, setSelectKeys] = useState(["platform"]);
  const history = useHistory();
  const [loginType, setLoginType] = useState();

  useEffect(() => {
    const { pathname } = window.location;
    const menu = menus.find(item => `${BASE_NAME}${item.route}` === pathname)
    setSelectKeys(() => [menu ? menu.key : 'platform'])
  }, [refresh])

  useEffect(() => {
    actions.onGlobalStateChange((state) => {
      const { loginType } = state;
      // 未登录 - 返回主页
      if (!loginType) {
        message.error("未检测到登录信息！");
        // return history.push("/");
        return;
      }
      setLoginType(loginType);
    }, true);
  }, [history]);

  const callback = (key) => {
    console.log('切换头部菜单',key);
    // 需要将信息发给主应用
    actions.setGlobalState({ platformTab: key })
  }
  return (
    <Router basename={BASE_NAME}>
      <section>
        <div style={{ color: 'red', padding: 20 }}>从主应用接受的登录信息：{loginType}</div>
        {/* <Menu
          onClick={() => setRefresh((refresh) => ++refresh)}
          selectedKeys={selectedKeys}
          mode="horizontal"
        >
          {menus.map((item) => (
            <Menu.Item key={item.key}>
              <Link to={item.route}>{item.title}</Link>
            </Menu.Item>
          ))}
        </Menu> */}
        <Tabs defaultActiveKey="platform" onChange={callback}>
          <TabPane tab="平台化管理" key="platform"></TabPane>
          <TabPane tab="SaaS化管理" key="sass">
            
          </TabPane>
          <TabPane tab="超管权限" key="auth">
            
          </TabPane>
        </Tabs>
        <Suspense fallback={null}>
          <Switch>
            <Route exact path='/' component={Home} />
            <Route path="/list" component={List} />
            <Route path="/sass" exact component={Home} />
            <Route path="/auth" exact component={Home} />
            <Route path="/sass/list" component={List} />
            <Route path="/auth/list" component={List} />
          </Switch>
        </Suspense>
      </section>
    </Router>
  )
}

export default App;